<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>基于WebSocket的用户登录</title>
</head>
<body>
<fieldset>
    <legend>
        基于WebSocket的用户登录——多终端同步显示操作过程
    </legend>
    <fieldset>
        <legend>
            用户登录
        </legend>
        用户名:<input type="text" id="userName"/><br>
        密  码:<input type="text" id="password"/><br>
        <input type="button" id="btnLogin" value="登录" onclick="login()"/>
    </fieldset>

    <fieldset>
        <legend>
            控制台消息
        </legend>
        <fieldset>
            <legend>
                要发送的消息
            </legend>
            <div id="needSendMessage"></div>
        </fieldset>
        <fieldset>
            <legend>
                接收到的消息
            </legend>
            <div id="receiveMessage"></div>
        </fieldset>
    </fieldset>
</fieldset>
</body>
<script type="text/javascript" src="js/InputChangeListen.js"></script>
<script type="text/javascript">
    var webSocketClientId;//与WebSocket服务器连接成功后,服务器端会返回一个clientId
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window || 'MozWebSocket' in window) {
        websocket = new WebSocket("ws://localhost:8080/websocket/userLogin");
    }
    else {
        alert('当前浏览器 Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function (event) {
        showReceiveMessage(event.data);
    };

    //连接成功建立的回调方法
    websocket.onopen = function (event) {
        showReceiveMessage(event.data);
    };

    /**
     * 根据接收到的操作消息执行相应的操作处理
     */
    function handleActionMessage(messageData) {
        var messageText = messageData.messageText;
        var action = messageData.action;
        if (action == "userLogin") {
            var paramObj = messageData.param;
            if (paramObj.success) {
                //为了看到接收到的返回的数据,这里延迟2秒后再跳转
                setTimeout(function () {
                    showReceiveMessage(messageText);
                    window.location.href = "webSocketClientList.html";
                }, 2000);

            } else {
                alert(messageText);
            }
        }else if(action=="inputText"){
            var paramObj = messageData.param;
            var inputText = paramObj.inputText;
            var controlId = paramObj.controlId;
            var fromWebSocketClientId = paramObj.fromWebSocketClientId;
            //如果消息的发送者不是自己,那么就接收发送过来的消息
            if(fromWebSocketClientId!=webSocketClientId){
                document.getElementById(controlId).value=inputText;
                //将监听用户名和密码输入的对象置为null,这样就只会接收消息,不会发送消息
                userNameChangeObj=null;
                passwordChangeObj=null;
            }
        }
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        //显示Websocket服务端推送回来的消息,测试代码
        showReceiveMessage(event.data);
        //解析接收到的消息，转成JSON对象
        var stringWebsocketMessage = JSON.parse(event.data);
        //根据消息类型进行数据处理
        var messageType = stringWebsocketMessage.messageType;
        if (messageType == "action") {//动作消息
            var messageData = stringWebsocketMessage.message;
            handleActionMessage(messageData);
        } else if (messageType == "sys") {//系统消息
            //记录服务器端返回的clientId
            webSocketClientId = stringWebsocketMessage.message.messageData.clientId;
        }
    };

    //连接关闭的回调方法
    websocket.onclose = function (event) {
        showReceiveMessage(webSocketClientId + "被WebSocket服务器端主动关闭连接了");
    };

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        //关闭本页面的WebSocket链接
        closeCurrentWebSocket();
    };
    var userNameChangeObj;
    var passwordChangeObj;
    window.onload=function(){
        /**
         * 发送输入的文字信息
         */
        function sendInputText(controlId,inputText){
            var paramObj = {};
            paramObj.inputText = inputText;
            paramObj.controlId = controlId;
            paramObj.fromWebSocketClientId=webSocketClientId;//发送消息的webSocketClient客户端
            sendActionMessage("inputText", paramObj);
        }

        //监听userName控件的内容输入
        userNameChangeObj=iChange("userName",function(){
            var inputText = this.value;
            if(userNameChangeObj!=null){
                sendInputText("userName",inputText);
            }
        });
        //监听password控件的内容输入
        passwordChangeObj=iChange("password",function(){
            var inputText = this.value;
            if(passwordChangeObj!=null){
                sendInputText("password",inputText);
            }
        });
    };

    /**
     * 将接收到的消息显示在网页上的receiveMessage Div中
     */
    function showReceiveMessage(innerHTML) {
        document.getElementById('receiveMessage').innerHTML = innerHTML;
    }

    //关闭当前页面的WebSocket连接
    function closeCurrentWebSocket() {
        if (websocket != null) {
            var paramObj = {};
            //需要关闭连接的webSocketClient集合
            paramObj.webSocketClientArr = [];
            var webSocketClient = {};
            webSocketClient.clientId = webSocketClientId;
            paramObj.webSocketClientArr.push(webSocketClient);
            //发送动作消息通知服务器端关闭当前的WebSocket的连接
            sendActionMessage("closeWebSocket", paramObj);
            //连接关闭的回调方法
            websocket.onclose = function (event) {
                showReceiveMessage(webSocketClientId + "被WebSocket服务器端主动关闭连接了");
            };
            websocket = null;
        } else {
            showReceiveMessage("websocket还没有连接");
        }
    }

    /**
     *发送操作动作Message
     * action 执行的动作
     * param 参数
     */
    function sendActionMessage(messageText, param) {
        //需要发送的消息数据
        var messageData = {};
        messageData.messageText = messageText;
        if (param != undefined) {
            messageData.param = param;
        }
        //发送消息
        sendMessage(messageData, "action");
    }


    /**
     * 发送消息
     * @param messageData 消息数据
     * @param messageType 消息类型
     */
    function sendMessage(messageData, messageType) {
        if (websocket != null) {
            //构建需要发送的消息对象
            var stringWebsocketMessage = {};
            stringWebsocketMessage.message = messageData;
            stringWebsocketMessage.messageType = messageType;//指明要发送的消息类型，WebSocket服务器端接收到消息后会根据消息类型进行数据推送
            //使用原生的JSON对象的stringify方法将stringWebsocketMessage转成JSON对象并使用WebSocket发送JSON对象
            var message = JSON.stringify(stringWebsocketMessage);
            showNeedSendMessage(message);//测试代码，将要发送的消息打印到页面上显示
            websocket.send(message);//发送消息
        } else {
            alert('请先连接WebSocket服务器')
        }

    }

    /**
     * 显示需要发送的消息
     */
    function showNeedSendMessage(innerHTML) {
        document.getElementById('needSendMessage').innerHTML = innerHTML;
    }

    /**
     *用户登录
     */
    function login() {
        var userName = document.getElementById("userName").value;
        var password = document.getElementById("password").value;
        var paramObj = {};
        paramObj.userName = userName;
        paramObj.password = password;
        sendActionMessage("userLogin", paramObj);
    }
</script>
</html>
